package com.qf.utils;

import com.qf.entity.Player;
import com.qf.entity.Room;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RoomManagerUtils {
    //基于房间号来管理房间（房间号-房间对象）
    private static Map<Integer, Room> roomMap = new ConcurrentHashMap<>();
    //基于玩家的连接管理房间（玩家连接对象-房间对象）
    private static Map<Session, Room> sessionRoomMap = new ConcurrentHashMap<>();

    //添加房间
    public static void putRoom(Integer rid, Room room) {
        roomMap.put(rid, room);
    }

    //添加房间
    public static void putRoom(Session session, Room room) {
        sessionRoomMap.put(session, room);
    }

    //根据房间号获得房间对象
    public static Room getRoom(Integer rid) {
        return roomMap.get(rid);
    }

    //根据session连接获得房间对象
    public static Room getRoom(Session session) {
        return sessionRoomMap.get(session);
    }

    //删除房间
    public static void removeRoom(Integer roomId) {
        Room removeRoom = roomMap.remove(roomId);
        //连带这sessionMap中的房间也要移除
        if (removeRoom != null) {
            Session session1 = removeRoom.getPlayer1().getSession();
            Session session2 = removeRoom.getPlayer2().getSession();

            //移除SessionMap中的房间
            sessionRoomMap.remove(session1);
            sessionRoomMap.remove(session2);

        }
    }

    public static void removeRoom(Session session) {
        Room removeRoom = sessionRoomMap.remove(session);
        if (removeRoom != null) {
            //根据房间id移除房间
            roomMap.remove(removeRoom.getRid());
            //从房间中找到对手玩家
            Player otherPlayer=removeRoom.getOtherPlayer(session);
            if(otherPlayer!=null){
                Session otherSession=removeRoom.getOtherPlayer(session).getSession();
                sessionRoomMap.remove(otherSession);
            }

        }
    }

    //返回所以房间列表
    public static List<Room> getRooms(){
        return new ArrayList<>(roomMap.values());
    }
}
